/*
 * @Author: your name
 * @Date: 2022-03-01 13:15:35
 * @LastEditTime: 2022-03-15 14:39:22
 * @LastEditors: Please set LastEditors
 * @Description: 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 * @FilePath: /visualNotes/src/service/login/index.ts
 */
import { auth, SUCCESS_CODE, ERROR_CODE } from "@/service";
import { getUserInfo } from "@/service/users";

export const userSign = (email: string, password: string) => {
  return auth
    .signUpWithEmailAndPassword(email, password)
    .then((res) => {
      return {
        code: SUCCESS_CODE,
        message: "邮件已发送成功",
      };
    })
    .catch((err) => {
      return {
        code: ERROR_CODE,
        message: "注册失败",
      };
    });
};

export const userLogin = (email: string, password: string) => {
  return auth
    .signInWithEmailAndPassword(email, password)
    .then(async (loginState) => {
      if (loginState.user) {
        const { uid } = auth.currentUser || {};
        const user = await getUserInfo(uid || "");
        return {
          code: SUCCESS_CODE,
          data: user,
          message: "登录成功",
        };
      }
      return { code: ERROR_CODE, data: null, message: "登录失败/邮箱未验证" };
    })
    .catch((err) => {
      return {
        code: ERROR_CODE,
        data: null,
        message: "登录失败/邮箱未验证/密码错误",
      };
    });
};

export const getCurrentUser = () => {
  const user = auth.currentUser;
  if (user) {
    return user;
  } else {
    return null;
  }
};

export const userLogout = () => {
  return auth
    .signOut()
    .then((res) => {
      return {
        code: SUCCESS_CODE,
        message: "登出成功",
      };
    })
    .catch((err) => ({
      code: ERROR_CODE,
      message: "失败，请重新尝试",
    }));
};
